package com.jeesite.modules.mo.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.v3.ApiException;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.config.MoneyParamter;
import com.jeesite.modules.config.PingtaiParam;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.mo.dao.MoShouyiDao;
import com.jeesite.modules.mo.dao.MoTixianDao;
import com.jeesite.modules.mo.entity.MoShouyi;
import com.jeesite.modules.mo.entity.MoTixian;
import com.jeesite.modules.mo.entity.MoTixianAli;
import com.jeesite.modules.mo.entity.MoUserDevice;
import com.jeesite.modules.pt.service.PtSettingService;
import com.jeesite.modules.rt.entity.RtDevice;
import com.jeesite.modules.rt.service.RtDeviceService;
import com.jeesite.modules.utils.ali.AlipayFundTransUniApiTransfer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Service
public class MoneyService {

    @Autowired
    private RtDeviceService rtDeviceService;
    @Autowired
    private MoShouyiService moShouyiService;
    @Autowired
    private IcUserService icUserService;
    @Autowired
    private MoShouyiDao moShouyiDao;
    @Autowired
    private MoTixianDao moTixianDao;
    @Autowired
    private MoUserDeviceService moUserDeviceService;
    @Autowired
    private MoTixianService moTixianService;

    @Value("${ali.appId}")
    private String aliAppId; //appID
    @Value("${ali.alipayPublicKeyUrl}")
    private String alipayPublicKeyUrl; //支付宝公钥
    @Value("${ali.rootCertPathUrl}")
    private String rootCertPathUrl; //支付宝根证书
    @Value("${ali.privateKeyUrl}")
    private String privateKeyUrl; //应用私钥文件
    @Value("${ali.appCertPathUrl}")
    private String appCertPathUrl; //应用公钥文件
    @Autowired
    private MoTixianAliService moTixianAliService;
    @Autowired
    private PtSettingService ptSettingService;


    @Transactional
    public boolean aliTixian(MoTixian moTixian) throws ApiException {

        moTixian.setWorkDate(new Date());
        moTixianService.save(moTixian);
        moTixian = moTixianService.get(moTixian);
        String id = moTixian.getId();//提现记录ID

        IcUser icUser = icUserService.get(moTixian.getUserId());
        String tixianAliId = null;
        AlipayFundTransUniApiTransfer transfer = new AlipayFundTransUniApiTransfer
                (aliAppId,privateKeyUrl,alipayPublicKeyUrl,rootCertPathUrl,appCertPathUrl);
        String result = transfer.transfer(moTixian.getId(),moTixian.getMoney().toString(),"提现",icUser.getZhifubaoMobile(),icUser.getShoukuanName());
        if(StringUtils.isNotEmpty(result)){
            JSONObject jsonObjectResult = JSONObject.parseObject(result);
            String statusStr = jsonObjectResult.getString("status");//状态 SUCCESS
            MoTixianAli moTixianAli = new MoTixianAli();
            moTixianAli.setTixianId(id);

            if("SUCCESS".equals(statusStr)){
                moTixianAli.setAliOrderId(jsonObjectResult.getString("order_id"));
                moTixianAli.setPayDate(DateUtils.parseDate(jsonObjectResult.getString("trans_date")));
                moTixianAli.setCommitStatus(statusStr);
                moTixianAli.setPayFundOrderId(jsonObjectResult.getString("pay_fund_order_id"));
                moTixianAliService.save(moTixianAli);
                tixianAliId = moTixianAli.getId();
                moTixian.setPayId(tixianAliId);
                moTixianService.save(moTixian);
                return true;
            }else{
                moTixianAli.setPayDate(new Date());
                if(StringUtils.isNotEmpty(jsonObjectResult.getString("message"))){
                    moTixianAli.setCommitStatus(jsonObjectResult.getString("message"));
                }
                if(StringUtils.isNotEmpty(jsonObjectResult.getString("fail_reason"))){
                    moTixianAli.setCommitStatus(jsonObjectResult.getString("fail_reason"));
                }
                moTixianAliService.save(moTixianAli);
                tixianAliId = moTixianAli.getId();
                moTixian.setPayId(tixianAliId);
                moTixian.setTixianStatus("4");
            }
        }
        moTixianService.save(moTixian);
        return false;
    }



    /**
     *
     * @param sn
     * @param workDate
     * @param amount
     */
    @Async("taskExecutor3")
    public void synUserShouyi(String sn, Date workDate, double amount){
        if(amount==0){
            return;
        }
        MoUserDevice deviceBySn = moUserDeviceService.findBySn(sn);
        if(deviceBySn==null){
            return;
        }
        String userId = deviceBySn.getUserId();
        if(StringUtils.isNotEmpty(userId)){
            IcUser icUser = icUserService.get(userId);
            //平台提成
            Double platformRatio = ptSettingService.getValueByKey(PingtaiParam.SHEBEI_CHOUCHENG)==null?0:Double.valueOf(ptSettingService.getValueByKey(PingtaiParam.SHEBEI_CHOUCHENG));
            //平台提成金额
            double platformJine = NumberUtils.div(NumberUtils.mul(amount, platformRatio),100,2);
            //平台抽成后剩余收益
            double shengyuShouyi = NumberUtils.sub(amount, platformJine);
            //代理商提成后的收益
            shengyuShouyi = dailishangTicheng(sn,workDate,shengyuShouyi);

            //用户自己的收益
            MoShouyi moShouyi = moShouyiDao.shouyiSumByUserSn(userId,1,workDate,sn);
            if(moShouyi==null){
                moShouyi = new MoShouyi();
            }
            moShouyi.setSn(sn);
            moShouyi.setUserId(userId);
            moShouyi.setWorkDate(workDate);
            moShouyi.setAmount(shengyuShouyi);
            moShouyi.setType(MoneyParamter.MONEY_SHOUYI_TYPE_SELF);
            moShouyi.setCreateTime(new Date());
            moShouyiService.save(moShouyi);

            MoUserDevice bySn = moUserDeviceService.findBySn(sn);
            //同步设备收益
            if(bySn != null){
                bySn.setYesterIcome(shengyuShouyi);
                //设备总收益
                double zongShouyi = moShouyiDao.shouyiSumByUser(userId, 1, null,sn);
                bySn.setSumIcome(zongShouyi);//设备总收益
                moUserDeviceService.save(bySn);
            }

            //同步到用户表
            synUserSumShouyi(userId);
        }
    }

    /**
     * 同步用户的总收益
     * @param userId
     */
    public void synUserSumShouyi(String userId){
        IcUser icUser = icUserService.get(userId);
        //总收益
        double zongShouyi = moShouyiDao.shouyiSumByUser(userId, 1, null,null);
        icUser.setSumIncome(zongShouyi);
        //昨日收益
        icUser.setYesterIncome(moShouyiDao.shouyiSumByUser(userId,1, DateUtils.getDate("yyyy-MM-dd",-1, Calendar.DATE),null));
        //总提成
        double zongTicheng = moShouyiDao.shouyiSumByUser(userId, 2, null,null);
        icUser.setSumTicheng(zongTicheng);
        //昨日提成
        icUser.setYesterTicheng(moShouyiDao.shouyiSumByUser(userId,2, DateUtils.getDate("yyyy-MM-dd",-1, Calendar.DATE),null));
        //钱包余额
        //提现金额
        double zongTixian = moTixianDao.moneyByUserId(userId, null, null);
        //总收入
        double zongShouru = NumberUtils.add(zongShouyi, zongTicheng);
        double yue = NumberUtils.sub(zongShouru, zongTixian);
        icUser.setYue(yue);
        icUserService.save(icUser);
    }

    /**
     * 代理商提成后的剩余收益
     */
    public double dailishangTicheng(String sn,Date workDate, double shengyuShouyi){
        MoUserDevice deviceBySn = moUserDeviceService.findBySn(sn);
        if(deviceBySn==null){
            return shengyuShouyi;
        }
        IcUser icUser = icUserService.get(deviceBySn.getUserId());
        String parentUserId = icUser.getParentUserId();
        if(StringUtils.isNotEmpty(parentUserId) && !"undefined".equals(parentUserId)){
            IcUser icUserParent = icUserService.get(parentUserId);
            //父有可能被删
            if(icUserParent!=null){
                Double agentRatio = icUserParent.getAgentRatio()!=null?icUserParent.getAgentRatio():0;
                if(agentRatio!=0){
                    //代理商提成(从剩余收益)
                    double agentAmount = NumberUtils.div(NumberUtils.mul(shengyuShouyi,agentRatio),100,2);
                    MoShouyi moShouyiDailishang = moShouyiDao.shouyiSumByUserSn(parentUserId,2,workDate,sn);
                    if(moShouyiDailishang==null){
                        moShouyiDailishang = new MoShouyi();
                    }

                    moShouyiDailishang.setSn(sn);
                    moShouyiDailishang.setUserId(parentUserId);
                    moShouyiDailishang.setWorkDate(workDate);
                    moShouyiDailishang.setAmount(agentAmount);
                    moShouyiDailishang.setNextUserId(icUser.getId());
                    moShouyiDailishang.setType(MoneyParamter.MONEY_SHOUYI_TYPE_TICHENG);
                    moShouyiDailishang.setCreateTime(new Date());
                    moShouyiService.save(moShouyiDailishang);
                    //同步到用户表
                    synUserSumShouyi(parentUserId);

                    //用户收益
                    shengyuShouyi = NumberUtils.sub(shengyuShouyi, agentAmount);
                }
            }
        }
        return shengyuShouyi;
    }
}
